//
// Created by YxMin on 2024/7/4.
//

#ifndef GAME_INPUT_H
#define GAME_INPUT_H
#include "Element.h"
#include <font.h>
#include <cstdio>
#include <UI.h>
const char BlackSpace[] = "                                                                   ";
class Input: public Element{
private:
    bool Focus = false;
    char* value;
    char* id;
    int inputPointer = 0;
    LPCTSTR placeholder = nullptr;
public:
    Input(char* id,int uid, int x1, int y1, int x2, int y2,int radius = 0, LPCTSTR placeholder = nullptr)
            : Element(uid, x1, y1, x2,y2,radius, nullptr) {
        this->id = id;
        value = new char[64];
        memset(value,0,64);//全设为空格
        value[0] = '_';
        if(radius > 0) {
            roundrect(area.left,area.top,area.right,area.bottom,radius,radius);
        } else {
            rectangle(area.left,area.top,area.right,area.bottom);
        }
        if (placeholder != nullptr) {
            this->placeholder = placeholder;
            showPlaceHolder();
        }
        RegisterInput(this);
    }
    ~Input() override {
        delete value;
    }
    char* getId() {
        return id;
    }
    char* getValue() {
        value[inputPointer] = 0;
        return value;
    }
    void draw() override {
        if(radius > 0) {
            roundrect(area.left,area.top,area.right,area.bottom,radius,radius);
        } else {
            rectangle(area.left,area.top,area.right,area.bottom);
        }
        onBlur();
    }
    bool isFocus() {
        return Focus;
    }
    void clearShow() {
        erase();
        if(radius > 0) {
            roundrect(area.left,area.top,area.right,area.bottom,radius,radius);
        } else {
            rectangle(area.left,area.top,area.right,area.bottom);
        }
    }
    void showPlaceHolder() {
        clearShow();
        settextcolor(LIGHTGRAY);
        SetFontSize((area.bottom-area.top)*2/3);
        showText(placeholder);
        RecoverFont();
    }
    void showInputText() {
        clearShow();
        settextcolor(BLACK);
        SetFontSize((area.bottom-area.top)*2/3);
        drawtext(value,&area,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
        RecoverFont();
    }
    void onFocus() {
        Focus = true;
        value[inputPointer] = '_';
        showInputText();
    }
    void onType(char c) {
        showInputText();
        if (c == 8 && inputPointer > 0) {
            value[inputPointer] = 0;
            inputPointer--;
            value[inputPointer] = '_';
        } else if(0x20 <= c && c <= 0x7e) {
            value[inputPointer] = c;
            inputPointer++;
            value[inputPointer] = '_';
        }
        showInputText();
    }
    void onBlur() {
        Focus = false;
        if (inputPointer == 0) {
            showPlaceHolder();
        } else {
            value[inputPointer] = 0;
            showInputText();
        }
    }

};
#endif //GAME_INPUT_H
